import com.surelution.lansao.OrderStatus;
import com.surelution.lansao.Role
import com.surelution.lansao.User
import com.surelution.lansao.UserRole
import com.surelution.lansao.vo.HttpClientContainer;

class BootStrap {

    def init = { servletContext ->
		//
		HttpClientContainer container = new HttpClientContainer()
		servletContext.setAttribute(HttpClientContainer.KEY, container)

		Role adminRole = Role.findByAuthority("ROLE-ADMIN")
		if(!adminRole) {
			adminRole = new Role(authority:"ROLE-ADMIN")
			adminRole.save(flush:true)
		}

		Role bizRole = Role.findByAuthority("ROLE-BUSINESS")
		if(!bizRole) {
			bizRole = new Role(authority:"ROLE-BUSINESS")
			bizRole.save(flush:true)
		}

		Role partnerRole = Role.findByAuthority("ROLE-PARTNER")
		if(!partnerRole) {
			partnerRole = new Role(authority:"ROLE-PARTNER")
			partnerRole.save(flush:true)
		}

		User user = User.findByUsername("admin")
		if(!user) {
			user = new User()
			user.username = "admin"
			user.password = "admin"
			user.enabled = true
			user.save(flush:true)
			
			UserRole userRole = new UserRole()
			userRole.user = user
			userRole.role = adminRole
			userRole.save(flush:true)
		}
	
		OrderStatus newOrder = OrderStatus.findByKey(OrderStatus.NEW)
		if(!newOrder) {
			newOrder = new OrderStatus(key:OrderStatus.NEW, label:"新建订单", description:"新建订单")
			newOrder.save(flush:true)
		}
		
		OrderStatus confirmedOrder = OrderStatus.findByKey(OrderStatus.CONFIRMED)
		if(!confirmedOrder) {
			confirmedOrder = new OrderStatus(key:OrderStatus.CONFIRMED, label:"已确认订单", description:"已确认订单")
			confirmedOrder.save(flush:true)
		}
		
		OrderStatus cancelledOrder = OrderStatus.findByKey(OrderStatus.CANCELLED)
		if(!cancelledOrder) {
			cancelledOrder = new OrderStatus(key:OrderStatus.CANCELLED, label:"已取消订单", description:"已取消订单")
			cancelledOrder.save(flush:true)
		}
		
		OrderStatus deliveredOrder = OrderStatus.findByKey(OrderStatus.DELIVERED)
		if(!deliveredOrder) {
			deliveredOrder = new OrderStatus(key:OrderStatus.DELIVERED, label:"已送出", description:"已送出")
			deliveredOrder.save(flush:true)
		}
		
		OrderStatus FINISHED = OrderStatus.findByKey(OrderStatus.FINISHED)
		if(!FINISHED) {
			FINISHED = new OrderStatus(key:OrderStatus.FINISHED, label:"完成", description:"完成")
			FINISHED.save(flush:true)
		}
    }
    def destroy = {
    }
}
